package com.hangzhou.welbeing.welbeinginstrument.fragement;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.hangzhou.welbeing.welbeinginstrument.R;
import com.hangzhou.welbeing.welbeinginstrument.activity.AllCircleActivity;
import com.hangzhou.welbeing.welbeinginstrument.activity.MyPostingOnCircleActivity;
import com.hangzhou.welbeing.welbeinginstrument.activity.NearManActivity;
import com.hangzhou.welbeing.welbeinginstrument.activity.TrueCircleActivity;
import com.hangzhou.welbeing.welbeinginstrument.adapter.PopularCircleAdapter;
import com.hangzhou.welbeing.welbeinginstrument.adapter.RecommendedAdapter;
import com.hangzhou.welbeing.welbeinginstrument.adapter.RecommendedCirclesAdapter;
import com.hangzhou.welbeing.welbeinginstrument.base.MyApplication;
import com.hangzhou.welbeing.welbeinginstrument.bean.AddCircleBean;
import com.hangzhou.welbeing.welbeinginstrument.bean.AttentionPostBean;
import com.hangzhou.welbeing.welbeinginstrument.bean.CancelAttentionPostBean;
import com.hangzhou.welbeing.welbeinginstrument.bean.CityWideAllCircleBean;
import com.hangzhou.welbeing.welbeinginstrument.bean.GuessYouLikeDateBean;
import com.hangzhou.welbeing.welbeinginstrument.bean.HotsCircleDataBean;
import com.hangzhou.welbeing.welbeinginstrument.bean.RecommendedPeopleDateBean;
import com.hangzhou.welbeing.welbeinginstrument.config.RBConstants;
import com.hangzhou.welbeing.welbeinginstrument.inteface.OnRecyclerViewItemClickListener;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.Callback;

import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;
import okhttp3.Response;

/**
 * 时间 2017 年 08 月 24.
 * 作者 Administrator  刘传华
 * 公司 杭州惟君医疗科技有限公司
 * 包名 com.hangzhou.welbeing.pregnant.welbeing_pregnant.fragement
 * 工程名 welbeing_pregnant
 *
 * @desc 发现  Fragment
 */
public class FindFragment extends Fragment {

    private static final String TAG ="FindFragment" ;
    @Bind(R.id.fragment_find_popular_circle_RecyclerView)
    RecyclerView fragmentFindPopularCircleXRecyclerView;
    @Bind(R.id.fragment_find_tv_add_more_circle)
    TextView fragmentFindTvAddMoreCircle;
    @Bind(R.id.fragment_find_rl_add_more_circle)
    RelativeLayout fragmentFindRlAddMoreCircle;
    @Bind(R.id.fragment_find_add_attention_RecyclerView)
    RecyclerView fragmentFindAddAttentionRecyclerView;
    @Bind(R.id.fragment_find_recommendation_RecyclerView)
    RecyclerView fragmentFindRecommendationRecyclerView;
    private Context mcontext = MyApplication.getMcontext();
    @Bind(R.id.fragment_find_rl_man_near)
    RelativeLayout fragmentFindRlManNear;

    private List<CityWideAllCircleBean.DataBean> databean;
    private RecommendedAdapter recommendedAdapter;
    private PopularCircleAdapter popularCircleAdapter;
    private List<HotsCircleDataBean.DataBean> mlist;
    private List<RecommendedPeopleDateBean.DataBean> mlist1;
    private RecommendedCirclesAdapter recommendedCirclesAdapter;
    private List<GuessYouLikeDateBean.DataBean> mlist2;
    private int lastVisibleItem;
    private int p1 = 1;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = View.inflate(mcontext, R.layout.fragment_find, null);
        ButterKnife.bind(this, view);

       /**--------------- 热门圈子----------------*/
        LinearLayoutManager layoutManager = new LinearLayoutManager(getContext());
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        fragmentFindPopularCircleXRecyclerView.setLayoutManager(layoutManager);



        LinearLayoutManager layoutManager_01 = new LinearLayoutManager(getContext());
        layoutManager_01.setOrientation(LinearLayoutManager.HORIZONTAL);
        fragmentFindAddAttentionRecyclerView.setLayoutManager(layoutManager_01);



        LinearLayoutManager layoutManager_02 = new LinearLayoutManager(getContext());
        layoutManager_02.setOrientation(LinearLayoutManager.VERTICAL);
        fragmentFindRecommendationRecyclerView.setLayoutManager(layoutManager_02);
//        recommendedAdapter = new RecommendedAdapter(mcontext, databean);
//        fragmentFindRecommendationRecyclerView.setAdapter(recommendedAdapter);
//        recommendedAdapter.setOnItemClickListener(new OnRecyclerViewItemClickListener() {
//            @Override
//            public void onItemClick(View view) {
//                int position = fragmentFindRecommendationRecyclerView.getChildAdapterPosition(view);
//                Intent intent = new Intent(getContext(), SimilarProfilePageFocusedActivity.class);
//                intent.putExtra("po_id",mlist2.get(position).po_id);
//                intent.putExtra("po_url",mlist2.get(position).po_url);
//                intent.putExtra("po_name",mlist2.get(position).po_name);
//                intent.putExtra("content",mlist2.get(position).content);
//                intent.putExtra("cus_logo",mlist2.get(position).cus_logo);
//                intent.putExtra("addtime",mlist2.get(position).addtime);
//                intent.putExtra("cus_name",mlist2.get(position).cus_name);
//                intent.putExtra("state",mlist2.get(position).state+"");
//                intent.putExtra("count",mlist2.get(position).count+"");
//                intent.putExtra("cus_id",mlist2.get(position).cus_id+"");
//                intent.putExtra("col",mlist2.get(position).col+"");
//                intent.putExtra("lCount",mlist2.get(position).lCount+"");
//                intent.putExtra("lstate",mlist2.get(position).lstate+"");
//                intent.putExtra("hits_like",mlist2.get(position).hits_like+"");
//
//                startActivity(intent);
//            }
//
//            @Override
//            public void onItemFirstButtonClick(View v, int position) {
//                int state = mlist2.get(position).state;
//                String cus_id = mlist2.get(position).cus_id;
//                if(state == 0){
//                    addAttentionPost(cus_id);
//                }else if(state == 1){
//                    cancelAttentionPost(cus_id);
//                }
//
//            }
//        });


        loadCircleData();
        return view;
    }

    @OnClick({R.id.fragment_find_rl_add_more_circle,R.id.fragment_find_rl_man_near})
    public void onViewClicked(View view) {
        switch (view.getId()){
            case R.id.fragment_find_rl_add_more_circle: //添加更多圈子
                Intent intent1 = new Intent(getContext(),AllCircleActivity.class);
                startActivity(intent1);
            break;
            case R.id.fragment_find_rl_man_near: //附近的人
                Intent intent =  new Intent(getContext(),NearManActivity.class);
                startActivity(intent);
                break;
        }
    }
    /**
     * @ddesc 初始化数据
     * */
    private void loadCircleData() {
        /**--------------- 热门圈子----------------*/
        loadHotsCircleData();
        /**--------------- 推荐的人----------------*/
        loadRecommendedPeopleDate();
        /**--------------- 为您推荐----------------*/
        loadRecommendedForYou(p1,8);
    }
    /**
     * @desc 推荐的人
     * */
    private void loadRecommendedPeopleDate() {
        SharedPreferences sp =mcontext.getSharedPreferences("second_app_internal_data", 0);
        String user_id = sp.getString("user_id","");
        OkHttpUtils
                .post()
                .url(RBConstants.SERVER_URL+RBConstants.RECOMMENDED_PEOPLE)
                .addParams("cus_id",user_id)
                .build()
                .execute(new Callback() {
                    @Override
                    public Object parseNetworkResponse(Response response, int id) throws Exception {
                        String parseNetworkResponse =  response.body().string();
                        //Log.e(TAG,"parseNetworkResponse========"+parseNetworkResponse);
                        Gson gson =  new Gson();
                        final RecommendedPeopleDateBean recommendedPeopleDateBean =   gson.fromJson(parseNetworkResponse,RecommendedPeopleDateBean.class);
                        if(recommendedPeopleDateBean.errorCode == 200){
                            MyApplication.getmHandler().post(new Runnable() {
                                @Override
                                public void run() {
                                    mlist1 = recommendedPeopleDateBean.data;
                                    if(mlist1 != null){
                                        recommendedCirclesAdapter = new RecommendedCirclesAdapter(mlist1,mcontext);
                                        fragmentFindAddAttentionRecyclerView.setAdapter(recommendedCirclesAdapter);
                                        recommendedCirclesAdapter.setOnItemClickListener(new OnRecyclerViewItemClickListener() {
                                            @Override
                                            public void onItemClick(View view) {
                                               int position = fragmentFindAddAttentionRecyclerView.getChildAdapterPosition(view);
                                                Intent intent  =  new Intent(getContext(),MyPostingOnCircleActivity.class);
                                                intent.putExtra("id",mlist1.get(position).id);
                                                intent.putExtra("num",mlist1.get(position).num);
                                                intent.putExtra("att",mlist1.get(position).att+"");
                                                intent.putExtra("cus_logo",mlist1.get(position).cus_logo+"");
                                                intent.putExtra("cus_name",mlist1.get(position).cus_name+"");
                                                startActivity(intent);
                                            }

                                            @Override
                                            public void onItemFirstButtonClick(View v, int position) {

                                            }
                                        });
                                    }

                                }
                            });
                        }else{
                            MyApplication.getmHandler().post(new Runnable() {
                                @Override
                                public void run() {
                                    Toast.makeText(getContext(),recommendedPeopleDateBean.errorMessage,Toast.LENGTH_LONG).show();
                                }
                            });
                        }
                        return null;
                    }

                    @Override
                    public void onError(Call call, Exception e, int id) {

                    }

                    @Override
                    public void onResponse(Object response, int id) {

                    }
                });

    }


    /**
     * @desc 热门圈子
     * */
    private void loadHotsCircleData() {
        SharedPreferences sp =mcontext.getSharedPreferences("second_app_internal_data", 0);
        String user_id = sp.getString("user_id","");
        OkHttpUtils
                .post()
                .url(RBConstants.SERVER_URL+RBConstants.HOSTS_CIRCLE)
                .addParams("cus_id", user_id)
                .build()
                .execute(new Callback() {
                    @Override
                    public Object parseNetworkResponse(Response response, int id) throws Exception {
                        String parseNetworkResponse =  response.body().string();
                       // Log.e(TAG,"parseNetworkResponse========"+parseNetworkResponse);
                        Gson gson =  new Gson();
                        final HotsCircleDataBean hotsCircleDataBean =   gson.fromJson(parseNetworkResponse,HotsCircleDataBean.class);
                        if(hotsCircleDataBean.errorCode == 200){
                            MyApplication.getmHandler().post(new Runnable() {
                                @Override
                                public void run() {
                                    mlist = hotsCircleDataBean.data;
                                    if(mlist!=null){
                                        popularCircleAdapter = new PopularCircleAdapter(mcontext);
                                        fragmentFindPopularCircleXRecyclerView.setAdapter(popularCircleAdapter);
                                        popularCircleAdapter.setOnItemClickListener(new OnRecyclerViewItemClickListener() {
                                            @Override
                                            public void onItemClick(View view) {
                                                int position = fragmentFindPopularCircleXRecyclerView.getChildAdapterPosition(view);
                                                Intent intent = new Intent(getContext(),TrueCircleActivity.class);
                                                intent.putExtra("circle_id",mlist.get(position).id);
                                                intent.putExtra("circle_num",mlist.get(position).num);
                                                intent.putExtra("circle_name",mlist.get(position).cat_name);
                                                intent.putExtra("circle_state",mlist.get(position).state+"");
                                                intent.putExtra("circle_url",mlist.get(position).url);
                                                startActivity(intent);

                                                SharedPreferences sp =mcontext.getSharedPreferences("second_app_internal_data", 0);
                                                SharedPreferences.Editor edit = sp.edit();
                                                edit.putString("circle_id",mlist.get(position).id);
                                                edit.commit();
                                            }

                                            @Override
                                            public void onItemFirstButtonClick(View v, int position) {
                                           /* Intent intent = new Intent(getContext(),TrueCircleActivity.class);
                                            startActivity(intent);*/
                                                String id =   mlist.get(position).id;
                                                int state =   mlist.get(position).state;
                                                if(state == 0){
                                                    addCircle(id);
                                                }else if(state == 1){
                                                    cancel(id);
                                                }
                                            }
                                        });
                                    }


                                }
                            });
                        }else{
                            MyApplication.getmHandler().post(new Runnable() {
                                @Override
                                public void run() {
                                    Toast.makeText(getContext(),hotsCircleDataBean.errorMessage,Toast.LENGTH_LONG).show();
                                }
                            });
                        }
                        return null;
                    }

                    @Override
                    public void onError(Call call, Exception e, int id) {

                    }

                    @Override
                    public void onResponse(Object response, int id) {

                    }
                });
    }
    /**
     * @desc 为您推荐
     * */
    private void loadRecommendedForYou(int p,int pp) {
        SharedPreferences sp =mcontext.getSharedPreferences("second_app_internal_data", 0);
        String user_id = sp.getString("user_id","");
        OkHttpUtils
                .post()
                .url(RBConstants.SERVER_URL+RBConstants.RECOMMEND_POST)
                .addParams("cus_id", user_id)
                .addParams("p", p+"")
                .addParams("pp", pp+"")
                .build()
                .execute(new Callback() {
                    @Override
                    public Object parseNetworkResponse(Response response, int id) throws Exception {
                        String parseNetworkResponse =  response.body().string();
                       // Log.e(TAG,"parseNetworkResponse========"+parseNetworkResponse);
                        Gson gson =  new Gson();
                        final GuessYouLikeDateBean guessYouLikeDateBean = gson.fromJson(parseNetworkResponse,GuessYouLikeDateBean.class);
                        if(guessYouLikeDateBean.errorCode == 200){
                            MyApplication.getmHandler().post(new Runnable() {
                                @Override
                                public void run() {
                                    mlist2 = guessYouLikeDateBean.data;
                                    if(mlist2 != null){
//                                       recommendedAdapter.addItem(mlist2);
//
//                                        //设置回到上拉加载更多
//                                        recommendedAdapter.changeMoreStatus(recommendedAdapter.NO_LOAD_MORE);
                                    }



                                }
                            });
                        }else{
                            MyApplication.getmHandler().post(new Runnable() {
                                @Override
                                public void run() {
                                    Toast.makeText(getContext(),guessYouLikeDateBean.errorMessage,Toast.LENGTH_LONG).show();
                                }
                            });
                        }

                        return null;
                    }

                    @Override
                    public void onError(Call call, Exception e, int id) {

                    }

                    @Override
                    public void onResponse(Object response, int id) {

                    }
                });

    }
    /**
     * @desc 取消关注
     * */
    private void cancelAttentionPost(String cus_id) {
        SharedPreferences sp =mcontext.getSharedPreferences("second_app_internal_data", 0);
        String user_id = sp.getString("user_id","");
        OkHttpUtils
                .post()
                .url(RBConstants.SERVER_URL+RBConstants.CANCLE_ATTENTION_POST)
                .addParams("cus_id",user_id)
                .addParams("followed", cus_id)
                .build()
                .execute(new Callback() {
                    @Override
                    public Object parseNetworkResponse(Response response, int id) throws Exception {
                        String parseNetworkResponse =  response.body().string();
                        //Log.e(TAG,"parseNetworkResponse========"+parseNetworkResponse);
                        Gson gson =  new Gson();
                        final CancelAttentionPostBean cancelAttentionPostBean = gson.fromJson(parseNetworkResponse,CancelAttentionPostBean.class);
                        if(cancelAttentionPostBean.errorCode == 200){
                            MyApplication.getmHandler().post(new Runnable() {
                                @Override
                                public void run() {
                                    Toast.makeText(getContext(),"取消关注成功",Toast.LENGTH_LONG).show();
                                    loadRecommendedForYou(p1,8);
                                }
                            });
                        }else{
                            MyApplication.getmHandler().post(new Runnable() {
                                @Override
                                public void run() {
                                    Toast.makeText(getContext(),cancelAttentionPostBean.errorMessage,Toast.LENGTH_LONG).show();
                                }
                            });
                        }

                        return null;
                    }

                    @Override
                    public void onError(Call call, Exception e, int id) {

                    }

                    @Override
                    public void onResponse(Object response, int id) {

                    }
                });

    }

    /**
     * @desc 添加关注
     * */
    private void addAttentionPost(String cus_id) {
        SharedPreferences sp =mcontext.getSharedPreferences("second_app_internal_data", 0);
        String user_id = sp.getString("user_id","");
        OkHttpUtils
                .post()
                .url(RBConstants.SERVER_URL+RBConstants.ADD_ATTENTION_POST)
                .addParams("cus_id", user_id)
                .addParams("followed",cus_id)
                .build()
                .execute(new Callback() {
                    @Override
                    public Object parseNetworkResponse(Response response, int id) throws Exception {
                        String parseNetworkResponse =  response.body().string();
                        //Log.e(TAG,"parseNetworkResponse========"+parseNetworkResponse);
                        Gson gson =  new Gson();
                        final AttentionPostBean attentionPostBean =  gson.fromJson(parseNetworkResponse,AttentionPostBean.class);
                        if(attentionPostBean.errorCode == 200){
                            MyApplication.getmHandler().post(new Runnable() {
                                @Override
                                public void run() {
                                    Toast.makeText(getContext(),"关注成功",Toast.LENGTH_LONG).show();
                                    loadRecommendedForYou(p1,8);

                                }
                            });
                        }else{
                            MyApplication.getmHandler().post(new Runnable() {
                                @Override
                                public void run() {
                                    Toast.makeText(getContext(),attentionPostBean.errorMessage,Toast.LENGTH_LONG).show();
                                }
                            });
                        }

                        return null;
                    }

                    @Override
                    public void onError(Call call, Exception e, int id) {

                    }

                    @Override
                    public void onResponse(Object response, int id) {

                    }
                });
    }

    private void addCircle(String id) {
        SharedPreferences sp = MyApplication.getMcontext().getSharedPreferences("second_app_internal_data", 0);
        String user_id = sp.getString("user_id","");
        OkHttpUtils
                .post()
                .url(RBConstants.SERVER_URL+RBConstants.ADD_CIRCLE)
                .addParams("cat_id", id)
                .addParams("cus_id", user_id)
                .build()
                .execute(new Callback() {
                    @Override
                    public Object parseNetworkResponse(Response response, int id) throws Exception {
                        String praiseParseNetworkResponse =  response.body().string();
                        Gson gson = new Gson();
                        //Log.e(TAG,"praiseParseNetworkResponse============>"+praiseParseNetworkResponse);
                        final AddCircleBean addCircleBean = gson.fromJson(praiseParseNetworkResponse,AddCircleBean.class);
                        if(addCircleBean.errorCode == 200 ){
                            MyApplication.getmHandler().post(new Runnable() {
                                @Override
                                public void run() {
                                    Toast.makeText(MyApplication.getMcontext(),"添加成功",Toast.LENGTH_SHORT).show();
                                    loadHotsCircleData();
                                }
                            });
                        }else{
                            MyApplication.getmHandler().post(new Runnable() {
                                @Override
                                public void run() {
                                    Toast.makeText(MyApplication.getMcontext(),addCircleBean.errorMessage,Toast.LENGTH_SHORT).show();
                                }
                            });
                        }
                        return null;
                    }

                    @Override
                    public void onError(Call call, Exception e, int id) {

                    }

                    @Override
                    public void onResponse(Object response, int id) {

                    }
                });
    }
    /**
     * @desc 取消
     * @param id*/
    private void cancel(String id) {
        SharedPreferences sp = MyApplication.getMcontext().getSharedPreferences("second_app_internal_data", 0);
        String user_id = sp.getString("user_id","");
        OkHttpUtils
                .post()
                .url(RBConstants.SERVER_URL+RBConstants.CANCEL_JOIN)
                .addParams("cat_id",id)
                .addParams("cus_id", user_id)
                .build()
                .execute(new Callback() {
                    @Override
                    public Object parseNetworkResponse(Response response, int id) throws Exception {
                        String praiseParseNetworkResponse =  response.body().string();
                        Gson gson = new Gson();
                        //Log.e(TAG,"praiseParseNetworkResponse============>"+praiseParseNetworkResponse);
                        final AddCircleBean addCircleBean = gson.fromJson(praiseParseNetworkResponse,AddCircleBean.class);
                        if(addCircleBean.errorCode == 200 ){
                            MyApplication.getmHandler().post(new Runnable() {
                                @Override
                                public void run() {
                                    Toast.makeText(MyApplication.getMcontext(),"已取消",Toast.LENGTH_SHORT).show();
                                    loadHotsCircleData();
                                }
                            });
                        }else{
                            MyApplication.getmHandler().post(new Runnable() {
                                @Override
                                public void run() {
                                    Toast.makeText(MyApplication.getMcontext(),addCircleBean.errorMessage,Toast.LENGTH_SHORT).show();
                                }
                            });
                        }
                        return null;
                    }

                    @Override
                    public void onError(Call call, Exception e, int id) {

                    }

                    @Override
                    public void onResponse(Object response, int id) {

                    }
                });
    }
    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }
}
